package com.hsgene.generator.util.generator;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 订单编号生成器
 *
 * @author wangbing
 * @version 1.0, 2018/6/29
 */
public class OrderGenerator extends AbstractGenerator {

    private final static String REDIS_ORDER_PREFIX_KEY = REDIS_PREFIX_KEY + "order:";

    private final static String INFIX_PATTERN = "yyyyMMddHHmmssSSS";

    private final static String DEFAULT_PREFIX = "";

    private final static Integer MAX_SUFFIX = 99999;

    private volatile static OrderGenerator instance;

    private OrderGenerator() {
    }

    public static OrderGenerator getInstance() {
        if (instance == null) {
            synchronized (OrderGenerator.class) {
                if (instance == null) {
                    instance = new OrderGenerator();
                }
            }
        }

        return instance;
    }

    @Override
    public String generate(String prefix) {
        return generate(prefix == null ? DEFAULT_PREFIX : prefix, LocalDateTime.now());
    }

    private String generate(String prefix, LocalDateTime currentTime) {
        StringBuilder builder = new StringBuilder();

        String infix = currentTime.format(DateTimeFormatter.ofPattern(INFIX_PATTERN));
        String redisKey = REDIS_ORDER_PREFIX_KEY + prefix + infix.substring(0, 14);
        Integer suffix = getIncrementSuffix(redisKey);
        if (suffix < 0 || suffix > MAX_SUFFIX) {
            // 当前后缀已经超过最大值限制，重新获取新的值
            return generate(prefix, currentTime.plusSeconds(1));
        }
        // 前缀、中缀、后缀
        builder.append(prefix)
                .append(infix)
                .append(String.format("%05d", suffix));

        return builder.toString();
    }
}
